package p.ithorns.framework.api;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * ApiHandlerMapping
 *
 * @author Ht.L
 * @date 2024-03-08 15:51
 * @since 1.0.0
 */
public class ApiHandlerMapping extends RequestMappingHandlerMapping {

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        ApiVersion annotation = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return buildFrom(annotation);
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        ApiVersion annotation = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return buildFrom(annotation);
    }

    private ApiVersionCondition buildFrom(ApiVersion version) {
        return null == version
                ? new ApiVersionCondition("1.0.0")
                : new ApiVersionCondition(version.value());
    }

}